# -*- coding: utf-8 -*-
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django.core.mail import send_mail

from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User

from codeshare.account.forms import UserLoginForm, RegisterFormUser, RegisterFormProfile
from codeshare.account import signals
from codeshare.account.models import Profile
def view_profile(request, uid):
    pass
def activate(request, uid, key):
    """View that activates a given user.  
        Links to this view should be unguessable, and sent via email to the user's email address."""
    
    try:
        user = User.objects.get(pk=uid)
    except User.DoesNotExist:
        raise Http404, "Invalid UID"
    
    #Verify that the keys match
    if key != user.profile.reg_key:
        #Invalid key
        raise Http404, "Invalid Registration Key"
    
    #Valid key and valid user
    user.is_active = True
    user.save()

    
    messages.success(request, "Your account has been activated. You can now login below.")
    return HttpResponseRedirect(reverse("account:login"))
def log_out(request):
    """Logs a user out.
        Fairly straightforward: log user out, then display a message telling them logout was successful."""
    
    logout(request)
    
    messages.success(request, "You have been successfully logged out.")
    return HttpResponseRedirect(reverse("main:index"))
def log_in(request):
    """Lets the user login.  
        If there is a "next" parameter in the URL, the user is redirected to that url after login"""
    
    if request.user.is_authenticated():
        #User's already logged in
        #Redirect them to the index page
        return HttpResponseRedirect(reverse("main:index"))
        
    if request.method == "GET":
        #User is requesting the page
        #Just display the form
        form = UserLoginForm(request)
    
    elif request.method == "POST":
        #User is trying to login
        form = UserLoginForm(request,request.POST)
        
        if form.is_valid():
            messages.success(request, "You have been logged in successfully.  Welcome, %s.  " % form.user.username)

            return HttpResponseRedirect(request.GET.get("next", reverse("main:index")))
    return render_to_response("accounts/login.html", RequestContext(request, {
        'form':form,
    }))
def register(request):
    """Registers a new user.
        Registration process uses email-activation.  
        - After the user is created, they are marked as inactive.  
        - An email is sent to them containing a link with a unique key.
        - After visiting the link in the email, the user is activated."""
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse("main:index"))
    
    if request.method == "GET":
        user_form = RegisterFormUser()
        profile_form = RegisterFormProfile()
    else:
        #The user is posting their registration -- process it
        user_form = RegisterFormUser(request.POST)
        profile_form = RegisterFormProfile(request.POST)
        
        print user_form.errors, profile_form.is_valid()
        
        if user_form.is_valid() and profile_form.is_valid():
            signals.registration_started.send(sender=None, user_form=user_form, profile_form=profile_form)
            #Valid forms...create the user and their profile
            udata = user_form.cleaned_data
            pdata = profile_form.cleaned_data
            
            user = User.objects.create_user(username=udata['username'], email=udata['email'], password=udata['password'])
            
            #User should start out inactive
            user.is_active = False
            user.save()
            
            profile = Profile.objects.create(
                user=user,
                bio=pdata.get("bio"),
                twitter=pdata.get("twitter"),
                reg_ip=request.META['REMOTE_ADDR'],
                last_ip=request.META['REMOTE_ADDR'])
            
            profile.reg_key = profile.generate_reg_key()
            profile.save()
            
            #Send the email
            message = """
                Hi %s, 
                    To activate your account on CodeShare, click the link below.
                    
                    localhost:8000/%s
                    
                    If you did not attempt to register on CodeShare, just ignore this message.
                
                CodeShare""" % (user.username, reverse("account:activate", args=[user.pk, profile.reg_key]))
            send_mail("Activate Your Account On CodeShare", message, '"CodeShare" <no-reply@codeshare.com>', [user.email])
                    
            signals.registration_finished.send(sender=None, user=user, profile=profile)
            
            messages.success(request, 
                "Your registration has been received.  Check %s for a link to activate your account." % user.email)
            return HttpResponseRedirect(reverse("main:index"))
    return render_to_response("accounts/register.html", RequestContext(request, {
        'user_form':user_form,
        'profile_form':profile_form
    }))